package com.hang.ad.sender.kafka;

import com.alibaba.fastjson.JSON;
import com.hang.ad.mysql.dto.MysqlRowData;
import com.hang.ad.sender.ISender;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Slf4j
@Component("kafkaSender")
public class KafkaSender implements ISender {
    @Value("${adconf.kafka.topic}")
    private String topic;
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;
    @Override
    public void sender(MysqlRowData mysqlRowData) {
        kafkaTemplate.send(topic, JSON.toJSONString(mysqlRowData));
    }
    @KafkaListener(topics = {"ad-search-mysql-data"}, groupId = "ad-search")
    public void processRowData(ConsumerRecord<?, ?> record){
        Optional<?> kafkaMsg = Optional.ofNullable(record.value());
        if (kafkaMsg.isPresent()){
            Object msg = kafkaMsg.get();
            MysqlRowData mysqlRowData = JSON.parseObject(msg.toString(), MysqlRowData.class);
            System.out.println("kafka process" + JSON.toJSONString(mysqlRowData));
        }
    }
}
